package com.tech.security.securityservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.tech.security.securityservice.model.LoginUser;
import com.tech.security.securityservice.service.UserService;
import com.tech.security.securityservice.util.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 认证器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public LoginUser login(LoginUser user) {

        // 使用security认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        if (authenticate.isAuthenticated()) {
            String jwtToken = JwtTokenUtils.getJwtToken(principal.getId());
            redisTemplate.opsForValue().set("login_"+principal.getId(), JSON.toJSONString(principal) ,1,TimeUnit.DAYS);
            principal.setToken(jwtToken);
        }

        return principal;
    }

    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisTemplate.delete("login:"+loginUser.getId());
    }

}
